package com.spring.library.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.spring.library.common.Result;
import com.spring.library.entity.Book;
import com.spring.library.entity.Record;
import com.spring.library.entity.User;
import com.spring.library.service.IBookService;
import com.spring.library.service.IRecordService;
import com.spring.library.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author danty
 * @since 2024-09-19
 */
@RestController
@CrossOrigin
@RequestMapping("/library/book")
public class BookController {
    @Autowired
    private IBookService bookService;
    @Autowired
    private IRecordService recordService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getBookList")
    public List<Book> getAll(){
        List<Book> list = bookService.list();
        return list;
    }

    /**
     * 新增图书
     * @param book
     * @return
     */
    @PostMapping("/addBook")
    public Result addBook(@RequestBody Book book) {
        String token = ThreadLocalUtil.get();
        System.out.println("token = " + token);

        // 从 Redis 中获取 User 对象
        User user = (User) redisTemplate.opsForValue().get(token);
        if (user == null) {
            return Result.error("登录已过期或无效");
        }

        String userRole = user.getUserRole();
        if (userRole.equals("ADMIN")) {
            if (bookService.getOne(new LambdaQueryWrapper<Book>().eq(Book::getBookIsbn, book.getBookIsbn())) != null) {
                return Result.error("图书ISBN已存在");
            }
            // 继续添加书籍的逻辑
            book.setBookUploadtime(LocalDateTime.now());
            bookService.save(book);
            return Result.success("添加成功");

        }
        return Result.error("权限不足");

    }


    /**
     * 通过id删除图书数据
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable("id") Integer id){
        String token = ThreadLocalUtil.get();
        User user = (User) redisTemplate.opsForValue().get(token);
        if (user == null) {
            return Result.error("非法删除图书操作");
        }
        String userRole = user.getUserRole();
        System.out.println("userRole = " + userRole);
        if(userRole.equals("ADMIN")) {
            LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>()
                    .eq(Book::getBookId, id);
            if (!bookService.remove(queryWrapper)) {
                return Result.error("用户id为空，无法删除");
            }
            return Result.success("删除成功");

        }
        return Result.error("权限操作有误");
    }

    /**
     * 归还图书操作
     * @param bookId
     * @return
     */
    @PostMapping("/reBack")
    public Result reBackBook(@RequestParam("bookId") Integer bookId) {
        String token = ThreadLocalUtil.get();
        User user = (User) redisTemplate.opsForValue().get(token);
        if (user == null) {
            return Result.error("非法修改图书操作");
        }
        if (user.getUserRole().equals("USER")) {
            UpdateWrapper<Book> eq = new UpdateWrapper<Book>()
                    .eq("book_borrower", user.getUserName())
                    .eq("book_id", bookId)
                    .set("book_borrower", null)
                    .set("book_borrowtime", null)
                    .set("book_returntime", null)
                    .set("book_status", 0);
            boolean result = bookService.update(eq);
            if (result) {
                Book byId = bookService.getById(bookId);
                DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String dataTime = LocalDateTime.now().format(fmt);
                Record record = new Record();
                record.setRecordBookname(byId.getBookName());
                record.setRecordBookisbn(byId.getBookIsbn());
                record.setRecordBorrower(user.getUserName());
                record.setRecordBorrowtime(dataTime);
                record.setRecordRemandtime(dataTime);
                recordService.save(record);
                return Result.success("归还成功!");
            }
            return Result.success("借阅数据有误!");
        }
        return Result.error("权限操作有误!");
    }

    /**
     * 借阅图书操作
     * @param bookId
     * @return
     */
    @PostMapping("/borrowBook")
    public Result borrowBook(@RequestParam("bookId") Integer bookId) {

        String token = ThreadLocalUtil.get();
        User user = (User) redisTemplate.opsForValue().get(token);
        if (user == null) {
            return Result.error("非法借阅图书操作");
        }
        // 检查用户当前借阅的书籍数量
        List<Book> borrowedBooks = bookService.list(new QueryWrapper<Book>()
                .eq("book_borrower", user.getUserName())
                .eq("book_status", 1));
        if (borrowedBooks.size() >= 3) {
            return Result.error("您已达到最大借阅数量，无法再借阅更多书籍");
        }
        if (user.getUserRole().equals("USER")) {
            Book byId = bookService.getById(bookId);
            if (byId.getBookStatus().equals("1")) {
                return Result.error("图书已被借阅，无法借阅");
            }
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String dataTime = LocalDateTime.now().format(fmt);
            String plusMonthsTime = LocalDateTime.now().plusMonths(1).format(fmt);
            UpdateWrapper<Book> wrapper = new UpdateWrapper<>();
            wrapper
                    .eq("book_id",bookId)
                    .set("book_status",1)
                    .set("book_borrower",user.getUserName())
                    .set("book_borrowtime",dataTime)
                    .set("book_returntime",plusMonthsTime);
            bookService.update(wrapper);
            return Result.success("图书借阅成功");
        }
        return Result.error("图书借阅失败");
    }
    /**
     * 获取用户当前借阅数据
     * @return
     */
    @GetMapping("/currentBorrowedBooks")
    public Result<List<Book>> getCurrentBorrowedBooks(){
        String token = ThreadLocalUtil.get();
        User user = (User) redisTemplate.opsForValue().get(token);
        if(user == null){
            return Result.error("非法查阅信息，请登录");
        }else{
            LambdaQueryWrapper<Book> queryWrapper = new LambdaQueryWrapper<Book>()
                    .eq(Book::getBookBorrower, user.getUserName());
            List<Book> books = bookService.list(queryWrapper);
            System.out.println("books = " + books);
            return Result.success(books);
        }
    }

    // 更新图书
    @PostMapping("/updateBook")
    public Result updateBook(@RequestBody Book book){
        UpdateWrapper<Book> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("book_id", book.getBookId())
                .set("book_name", book.getBookName())
                .set("book_isbn", book.getBookIsbn())
                .set("book_press", book.getBookPress())
                .set("book_author", book.getBookAuthor())
                .set("book_pagination", book.getBookPagination())
                .set("book_price", book.getBookPrice())
                .set("book_uploadtime", book.getBookUploadtime())
                .set("book_status", book.getBookStatus())
                .set("book_borrower", book.getBookBorrower())
                .set("book_borrowtime", book.getBookBorrowtime())
                .set("book_returntime", book.getBookReturntime());
        boolean result = bookService.update(updateWrapper);
        if (result) {
            return Result.success("修改图书成功!");
        } else {
            return Result.error("修改失败,图书可能不存在或是出现错误!");
        }

    }


}
